package mylab.base;

import cn.hutool.core.util.ReflectUtil;
import com.fasterxml.jackson.annotation.JsonValue;
import mylab.base.exceptions.AppRuntimeException;

import java.io.Serializable;
import java.lang.reflect.Field;

public interface LabelValue<V extends Serializable> extends Serializable {
    String DEFAULT_VALUE_NAME = "value";

    String DEFAULT_LABEL_NAME = "label";

    @SuppressWarnings("unchecked")
    default V getValue() {
        Field field = ReflectUtil.getField(this.getClass(), DEFAULT_VALUE_NAME);
        if (field == null)
            return null;
        try {
            field.setAccessible(true);
            return (V) field.get(this);
        } catch (IllegalAccessException e) {
            throw new AppRuntimeException(e);
        }
    }

    @JsonValue
    default String getLabel() {
        Field field = ReflectUtil.getField(this.getClass(), DEFAULT_LABEL_NAME);
        if (field == null)
            return null;
        try {
            field.setAccessible(true);
            return field.get(this).toString();
        } catch (IllegalAccessException e) {
            throw new AppRuntimeException(e);
        }
    }
}
